/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.udesc.pges.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;

import static io.netty.handler.codec.http.HttpHeaders.Names.*;
import static io.netty.handler.codec.http.HttpHeaders.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpVersion.*;
import java.net.UnknownHostException;

/**
 *
 * @author Ricardo Schroeder
 */
class HttpNettyServerMongoHandler extends ChannelInboundHandlerAdapter {

    public static MongoClient mongoClient;

    public HttpNettyServerMongoHandler() throws Exception {
        //MongoClient mongoClient = new MongoClient("10.1.1.102", 27017);
        //db = mongoClient.getDB("monografia");
    }

    private synchronized MongoClient getClient() throws UnknownHostException {
        if (mongoClient == null) {
            mongoClient = new MongoClient("127.0.0.1", 27017);
        }
        return mongoClient;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) msg;
            String uri = req.getUri();
            FullHttpResponse response = null;
            if (7 == uri.length()) {
                uri = uri.substring(1);
                DB db = getClient().getDB("monografia");
                db.requestStart();
                db.requestEnsureConnection();
                DBCollection url = db.getCollection("url");
                //BasicDBObject query = new BasicDBObject("hash", uri);
                DBObject resul = url.findOne(new BasicDBObject("hash", uri));
                if (resul != null) {
                    String urlRedirect = "http://" + resul.get("url");
                    response = new DefaultFullHttpResponse(HTTP_1_1, MOVED_PERMANENTLY);
                    response.headers().set(LOCATION, urlRedirect);
                } else {
                    response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
                }
                db.requestDone();
            } else {
                response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND);
            }
            boolean keepAlive = isKeepAlive(req);
            response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
            if (!keepAlive) {
                ctx.write(response).addListener(ChannelFutureListener.CLOSE);
            } else {
                response.headers().set(CONNECTION, Values.KEEP_ALIVE);
                ctx.write(response);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
